package com.shadow.baiqun.delegate.send.detail;

import android.device.ScanDevice;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.Group;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.send.adapter.SendDetailAdapter;
import com.shadow.baiqun.delegate.send.order.OrderDelegate;
import com.shadow.baiqun.event.ScanInfoEvent;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zhangyu
 * @date 2018/7/26
 */

public class SendDetailDelegate extends RxShadowDelegate {
    private static final String TASK_ID = "taskId";
    private static final String HAS_USER = "hasUser";

    public static SendDetailDelegate create(String taskId, boolean hasUser) {
        final SendDetailDelegate contentDelegate = new SendDetailDelegate();
        final Bundle bundle = new Bundle();
        bundle.putString(TASK_ID, taskId);
        bundle.putBoolean(HAS_USER, hasUser);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    private static final int PAGE_SIZE = 50;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.tv_count)
    TextView mTvCount;
    @BindView(R2.id.group)
    Group mGroup;
    private SendDetailAdapter mDetailAdapter;
    private int mNextRequestPage = 1;
    private boolean isRequesting = false;
    private String mTaskId;
    private boolean hasUser;

    private ScanDevice mScanDevice;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mTaskId = bundle.getString(TASK_ID);
            hasUser = bundle.getBoolean(HAS_USER);
        }
        mScanDevice = new ScanDevice();
        //    广播输出
        mScanDevice.setOutScanMode(0);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_send_detail;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("装车信息表详情");
            mToolbar.inflateMenu(R.menu.order);
            mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    int i = item.getItemId();
                    if (i == R.id.menu_order) {
                        checkOrder();
                    }
                    return true;
                }
            });
        }
        mGroup.setVisibility(hasUser ? View.VISIBLE : View.GONE);
        mDetailAdapter = new SendDetailAdapter(R.layout.item_send_detail, null);
        mDetailAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        LinearSnapHelper linearSnapHelper = new LinearSnapHelper();
        linearSnapHelper.attachToRecyclerView(mRecyclerView);
        mDetailAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
        if (mDetailAdapter.getEmptyView() != null) {
            mDetailAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
        mRecyclerView.setAdapter(mDetailAdapter);
    }

    /**
     * 查看指示单
     */
    private void checkOrder() {
        start(OrderDelegate.create(mTaskId));
    }

//    @Override
//    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
//        super.onLazyInitView(savedInstanceState);
//        refresh();
//    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refresh();
    }
    //刷新
    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mDetailAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }
    }

    private void requestData(final boolean isRefresh) {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/sendCar/carDetile")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mDetailAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        SendDetailConverter sendDetailConverter = new SendDetailConverter();
                        setData(isRefresh, sendDetailConverter.convert(response, new SendDetailConverter.OnCalculateListener() {
                            @Override
                            public void onNotCheckNumber(int number, int total) {
                                if (mTvCount != null) {
                                    mTvCount.setText(String.format(Locale.CHINA,
                                            "%s/%d", String.valueOf(total - number), number));
                                }
                            }
                        }));
                        isRequesting = false;
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDetailAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                    }
                })
                .params("taskid", mTaskId)
                .params("pageNum", mNextRequestPage)
                .params("pageSize", PAGE_SIZE)
                .build()
                .unRestGet());
    }

    private void setData(boolean isRefresh, List<SendDetailEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mDetailAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mDetailAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mDetailAdapter.loadMoreEnd(isRefresh);
        } else {
            mDetailAdapter.loadMoreComplete();
        }
    }

    private void loadMore() {
        requestData(false);
    }

    @OnClick(R2.id.tv_check)
    public void onCheckOrder() {
        if (!mScanDevice.isScanOpened()) {
            mScanDevice.openScan();
        }
        mScanDevice.startScan();
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
        refresh();
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void scanEvent(ScanInfoEvent event) {
        doCheck(event.mInfo);
    }

    private void doCheck(String code) {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/sendCar/checkOrder")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = new ResultConverter().getCode(response);
                        String msg = new ResultConverter().getMsg(response);
//                        if (code == 0) {
//                            ToastUtils.showToast(getContext(), "未找到该条码!");
//                        } else
                        if (code == 1) {
                            ToastUtils.showToast(getContext(), "成功!");
                        } else {
                            ToastUtils.showToast(getContext(), msg);
                        }
                        refresh();
// else if (code == 2) {
//                            ToastUtils.showToast(getContext(), "调整装车信息表新增成功!");
//                            refresh();
//                        } else if (code == -2) {
//                            ToastUtils.showToast(getContext(), "批次不对!");
//                        } else if (code == 3) {
//                            ToastUtils.showToast(getContext(), "数量足够不需要继续添加!");
//                        } else if (code == 4) {
//                            ToastUtils.showToast(getContext(), "该零件已经扫描过!");
//                        } else if (code == -3) {
//                            ToastUtils.showToast(getContext(), "不在本次装车计划中!");
//                        } else {
//                            ToastUtils.showToast(getContext(), "系统错误!");
//                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), msg);
                    }
                })
                .params("tabCode", code)
                .params("taskid", mTaskId)
                .build()
                .unRestGet());
    }

    @OnClick(R2.id.tv_confirm)
    public void onConfirm() {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/sendCar/sureCar")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = new ResultConverter().getCode(response);
                        if (code == -2) {
                            ToastUtils.showToast(getContext(), "零件数量不足，不能提交!");
                        } else if (code == 1) {
                            ToastUtils.showToast(getContext(), "成功!");
                            pop();
                        } else {
                            ToastUtils.showToast(getContext(), "系统错误!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), msg);
                    }
                })
                .params("taskid", mTaskId)
                .build()
                .unRestGet());
    }

}
